package com.fruits.login.handler;

import com.fruits.login.annotation.DeCrypt;
import com.fruits.login.dto.CryptDto;
import com.sghd.common.utils.codec.CryptUtils;
import com.sghd.common.utils.json.JsonUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

/**
 * @author frank
 * @date 2019-01-29 15:54
 * @desc
 **/
public class CryptMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(DeCrypt.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception{
        //解密
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();

            char[] buf = new char[1024];
            int rd;
            while((rd = reader.read(buf)) != -1){
                sb.append(buf, 0, rd);
            }

            try {
                CryptDto cryptDto = JsonUtils.string2Object(sb.toString(), CryptDto.class);
                String deStr = CryptUtils.decryptDESIV(cryptDto.getBody(),"urBS2Qa@");
//                System.out.println("收到：" + deStr);
                return JsonUtils.string2Object(deStr, parameter.getParameterType());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
